package com.lwy.qiuchao.auth.controller;


import com.alibaba.fastjson.TypeReference;
import com.lwy.common.constant.AuthServerConstant;
import com.lwy.common.exception.BizCodeEnume;
import com.lwy.common.utils.R;
import com.lwy.qiuchao.auth.feign.MemberFeignService;
import com.lwy.qiuchao.auth.feign.ThirdPartyFeignService;
import com.lwy.qiuchao.auth.vo.MemeberEntityVo;
import com.lwy.qiuchao.auth.vo.UserLoginVo;
import com.lwy.qiuchao.auth.vo.UserRegistVo;
import com.lwy.qiuchao.member.entity.MemeberEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author shkstart
 * @date 2020/12/03 -15:59
 */
@Controller
public class LoginController {

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCodeMessage(@RequestParam("phone") String phone) {
        String rediscode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(rediscode)) {
            long l = Long.parseLong(rediscode.split("_")[1]);
            if (System.currentTimeMillis() - 1 < 60 * 1000) {
                //60s内不能重发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        String subString = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, subString, 10, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }


    @PostMapping("/regist")
    public String regist(@RequestBody @Valid UserRegistVo userRegistVo,
                         BindingResult result,
                         RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            /**
             * //TODO 重定向携带数据，利用session原理，将数据存放到session中
             * 只要调到下一个页面取出这个数据后，session里面的数据就会删掉
             *
             * //TODO 1、分布式下的session问题
             * */
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.qiuchao.com/regist.html";
            //用户注册->/regist[post] --->转发/reg.html(路径映射默认都是get方式访问)
        }

        String code = userRegistVo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                //删除验证码，令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
                //验证码通过。  真正远程服务调用进行注册
                R regist = memberFeignService.regist(userRegistVo);
                if (regist.getcode() == 0) {
                    //注册成功
                    return "redirect:/5";
                } else {
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", regist.getData(new TypeReference<String>() {
                    }));
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.qiuchao.com/regist.html";
                }


            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.qiuchao.com/regist.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.qiuchao.com/regist.html";
        }
    }

    @ResponseBody
    @GetMapping("/exit")
    public R quit(HttpServletResponse response){
        Cookie killMyCookie = new Cookie("token", null);
        killMyCookie.setMaxAge(0);
        killMyCookie.setPath("/");
        response.addCookie(killMyCookie);
        return R.ok();
    }

    @PostMapping("/login")
    @ResponseBody
    public R Login(@RequestBody UserLoginVo loginVo, RedirectAttributes ra, HttpServletResponse response, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String tokenValue = null;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName()=="token"){
                    MemeberEntity memeberEntity = memberFeignService.memberInfo(cookie.getValue());
                    return R.ok().setData(memeberEntity);
                }
            }
        }

        R login = memberFeignService.login(loginVo);
        if (login.getcode() == 0) {
            MemeberEntityVo memeberEntityVo = login.getData("data", new TypeReference<MemeberEntityVo>() {
            });
            String token = memeberEntityVo.getToken();
            Cookie cookie = new Cookie("token",token);
            response.addCookie(cookie);



            return R.ok().setData(memeberEntityVo);

        } else {
            Map<String, String> errors = new HashMap<>();
            String data = login.getData("msg", new TypeReference<String>() {
            });
            errors.put("msg", data);
            ra.addFlashAttribute("errors", errors);
            return R.error(BizCodeEnume.LOGIN_FAILED.getCode(),BizCodeEnume.LOGIN_FAILED.getMsg());
        }
    }
}